import strHtml from "./CheckOutPage.html";
import { DomUtils } from "../../utils/DomUtils";
import { productService } from "../../services/productService";

export class CheckOutPage {
  constructor() {
    this.dom = null;
    this.cart = [];
    this.productList = [];
  }

  async render() {
    this.dom = DomUtils.convertToDom(strHtml);
    await this._loadData();
    this._renderOrder();
    this._bindSubmit();
    // 用户离开结算页时自动清除 buyNowProduct
    window.addEventListener("hashchange", function clearBuyNow() {
      if (location.hash !== "#/check-out") {
        localStorage.removeItem("buyNowProduct");
        window.removeEventListener("hashchange", clearBuyNow);
      }
    });
    return this.dom;
  }

  async _loadData() {
    try {
      // 从后端获取最新商品数据
      const response = await productService.getAll();
      this.productList = response;

      // 优先读取 buyNowProduct
      const buyNow = localStorage.getItem("buyNowProduct");
      if (buyNow) {
        const buyNowItem = JSON.parse(buyNow);
        // 获取最新商品信息
        const product = this.productList.find(
          (p) => p.productId === buyNowItem.productId
        );
        if (product) {
          this.cart = [
            {
              ...buyNowItem,
              name: product.productName,
              price: product.productPrice,
              stock: product.stock,
              productImg:
                product.productImg ||
                product.img ||
                "https://via.placeholder.com/80",
            },
          ];
        } else {
          this.cart = [];
          alert("商品已下架或不存在！");
        }
      } else {
        // 从本地存储获取购物车数据
        const cartData = JSON.parse(localStorage.getItem("cart") || "[]");
        // 更新购物车中的商品信息
        this.cart = cartData
          .map((item) => {
            const product = this.productList.find(
              (p) => p.productId === item.productId
            );
            if (product) {
              return {
                ...item,
                name: product.productName,
                price: product.productPrice,
                stock: product.stock,
                productImg:
                  product.productImg ||
                  product.img ||
                  "https://via.placeholder.com/80",
              };
            }
            return null;
          })
          .filter((item) => item !== null);

        // 如果购物车数据有变化，更新本地存储
        if (this.cart.length !== cartData.length) {
          localStorage.setItem("cart", JSON.stringify(this.cart));
          if (this.cart.length === 0) {
            alert("购物车中的商品已下架或不存在！");
            location.hash = "#/cart";
            return;
          }
        }
      }
    } catch (error) {
      console.error("加载结算数据失败:", error);
      this.cart = [];
      this.productList = [];
    }
  }

  _renderOrder() {
    const list = this.dom.querySelector("#order-items");
    const subtotalEl = this.dom.querySelector("#subtotal");
    const totalEl = this.dom.querySelector("#order-total");

    if (!list || !subtotalEl || !totalEl) return;

    let subtotal = 0;
    list.innerHTML = "";

    if (this.cart.length === 0) {
      list.innerHTML = `
        <li class="text-center py-3">
          <p class="text-muted mb-0">没有可结算的商品</p>
        </li>
      `;
      subtotalEl.innerText = "￥0.00";
      totalEl.innerText = "￥0.00";
      return;
    }

    this.cart.forEach((item) => {
      const itemTotal = item.price * item.quantity;
      subtotal += itemTotal;

      const li = document.createElement("li");
      li.className = "d-flex justify-content-between mb-2 align-items-start";
      li.innerHTML = `
        <span>${item.name}</span>
        <span class="text-end">
          <span style="display:block;">× ${item.quantity}</span>
          <span class="text-danger fs-5" style="display:block;">￥${itemTotal.toFixed(
            2
          )}</span>
        </span>
      `;
      list.appendChild(li);
    });

    subtotalEl.innerText = `￥${subtotal.toFixed(2)}`;

    const shippingRadioList = this.dom.querySelectorAll(
      "input[name='shipping']"
    );
    shippingRadioList.forEach((radio) => {
      radio.addEventListener("change", () => this._updateTotal());
    });

    this._updateTotal();
  }

  _updateTotal() {
    const subtotal = parseFloat(
      this.dom.querySelector("#subtotal").innerText.replace("￥", "")
    );
    const shipping = parseFloat(
      this.dom.querySelector("input[name='shipping']:checked").value
    );
    const total = subtotal + shipping;
    this.dom.querySelector("#order-total").innerText = `￥${total.toFixed(2)}`;
  }

  _bindSubmit() {
    const btn = this.dom.querySelector("#place-order-btn");
    const form = this.dom.querySelector("#checkout-form");

    btn.addEventListener("click", () => {
      if (!form.reportValidity()) return;

      // 获取用户选择的支付方式
      const payMethod = this.dom.querySelector(
        "input[name='payment']:checked"
      ).value;

      // 获取配送方式
      const shippingRadio = this.dom.querySelector(
        "input[name='shipping']:checked"
      );
      const shippingMethod = shippingRadio ? shippingRadio.value : "";
      const shippingText = shippingRadio
        ? shippingRadio.getAttribute("data-label") ||
          shippingRadio.nextSibling?.textContent?.trim() ||
          ""
        : "";

      // 订单主商品（第一个商品）
      const firstItem = this.cart[0] || {};
      // 获取用户列表（假设保存在localStorage的userList字段）
      const userList = JSON.parse(localStorage.getItem("userList") || "[]");
      const getUsernameById = (userId) => {
        const user = userList.find((u) => u.userId === userId);
        return user ? user.username : "";
      };
      // 卖家名字（通过userId查找username）
      const sellerName = getUsernameById(firstItem.userId) || "";

      // 获取订单总金额（含运费）
      const subtotal = parseFloat(
        this.dom.querySelector("#subtotal").innerText.replace("￥", "")
      );
      const shippingFee = parseFloat(shippingMethod || 0);
      const totalAmountWithShipping = subtotal + shippingFee;

      // 订单数据
      const orderData = {
        orderNo: this._generateOrderNo(),
        date: new Date().toLocaleDateString(),
        name: this.dom.querySelector("#firstName").value,
        phone: this.dom.querySelector("#phone").value,
        email: this.dom.querySelector("#email").value,
        address: this.dom.querySelector("#address").value,
        payment: payMethod,
        shippingMethod: shippingMethod,
        shippingText: shippingText,
        shippingFee: shippingFee, // 保存运费
        totalAmount: totalAmountWithShipping, // 商品总价+运费
        sellerName: sellerName,
        productImg: firstItem.productImg || "",
        productName: firstItem.name || "",
        price: firstItem.price || 0,
        count: firstItem.quantity || 0,
        totalPrice: (firstItem.price || 0) * (firstItem.quantity || 0),
        items: this.cart.map((item) => ({
          productId: item.productId,
          name: item.name,
          price: item.price,
          quantity: item.quantity,
          totalPrice: item.price * item.quantity,
          productImg: item.productImg || "",
          shopName: item.shopName || item.sellerName || "",
        })),
        status: "待收货",
        commentStatus: "未评",
        logistics: [
          { name: "拍下商品", time: new Date().toLocaleString(), done: true },
          {
            name: "付款到支付宝",
            time: new Date().toLocaleString(),
            done: true,
          },
          { name: "卖家发货", time: "", done: false },
          { name: "确认收货", time: "", done: false },
          { name: "评价", time: "", done: false },
        ],
      };

      // 从localStorage获取现有订单
      let orders = [];
      try {
        const savedOrders = localStorage.getItem("orders");
        if (savedOrders) {
          orders = JSON.parse(savedOrders);
        }
      } catch (error) {
        console.error("读取订单数据失败:", error);
      }

      // 添加新订单
      orders.unshift(orderData); // 将新订单添加到数组开头

      // 保存更新后的订单数据
      try {
        localStorage.setItem("orders", JSON.stringify(orders));
        console.log("订单数据已保存到localStorage");
      } catch (error) {
        console.error("保存订单数据失败:", error);
        alert("保存订单失败，请重试");
        return;
      }

      // 清除购物车数据
      localStorage.removeItem("cart");
      localStorage.removeItem("buyNowProduct");

      // 创建支付确认弹窗
      const modalHtml = `
        <div class="modal fade" id="paymentConfirmModal" tabindex="-1">
          <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title">确认支付</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
              </div>
              <div class="modal-body text-center">
                <h4 class="mb-4">订单总金额：${totalAmountWithShipping.toFixed(
                  2
                )}</h4>
                <div class="d-flex justify-content-center gap-3">
                  <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                  <button type="button" class="btn btn-primary" id="confirmPaymentBtn">确认支付</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      `;

      // 添加弹窗到DOM
      const modalContainer = document.createElement("div");
      modalContainer.innerHTML = modalHtml;
      document.body.appendChild(modalContainer);

      // 显示弹窗
      const modal = new bootstrap.Modal(
        document.getElementById("paymentConfirmModal")
      );
      modal.show();

      // 绑定确认支付按钮事件
      document
        .getElementById("confirmPaymentBtn")
        .addEventListener("click", () => {
          // 关闭弹窗
          modal.hide();

          // 跳转到订单页面
          location.hash = "#/my-orders";
        });

      // 弹窗关闭后移除DOM
      document
        .getElementById("paymentConfirmModal")
        .addEventListener("hidden.bs.modal", function () {
          this.remove();
        });
    });
  }

  _generateOrderNo() {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const random = Math.floor(Math.random() * 1000000)
      .toString()
      .padStart(6, "0");
    return `${year}${month}${day}${random}`;
  }
}
